#include "CTimer.h"

#ifdef WIN_32
#include <windows.h>
#elif defined LINUX
#include <time.h>
#include <unistd.h>
#endif

#include <algorithm>


CTimer::CTimer(void): m_dLastPCR(0), m_dLastSysTime(0){
}



CTimer::~CTimer(void){
}

void CTimer::setCurrentPCR(unsigned long long PCR){
	if (PCR > 0 ){
		unsigned long long dSysTime = 0;
#ifdef WIN_32
		SYSTEMTIME st;    
		GetSystemTime(&st);
		dSysTime = st.wMinute*(60*1000) + st.wSecond*1000+ st.wMilliseconds;
#elif defined LINUX
		time_t sec;
		sec = time (NULL);
#endif 

		if (m_dLastPCR > 0 ){
			unsigned long long dCurrentFiddDiff = PCR - m_dLastPCR;
			double totalSeconds1 = PCR / (double)90000;
			double totalSeconds2 = m_dLastPCR / (double)90000;
			double dDiff = totalSeconds1 - totalSeconds2;
			int nSleepTime = (int)(dDiff*1000);
			int nRealTime = (int)(dSysTime - m_dLastSysTime);
			if (nSleepTime > nRealTime && nRealTime>0){

#ifdef WIN_32
				//Sleep(min((nSleepTime - nRealTime)/1, 1000));
				Sleep(1);
#elif defined LINUX
				usleep(1000); //convert to microseconds
#endif 
			}
		}
		m_dLastPCR = PCR;
		m_dLastSysTime = dSysTime;
	}
}
